//
//  EDQuestionSettingViewController.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/7/14.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDQuestionSettingViewController.h"
#import "EDInfoSettingView.h"
#import "CGXPickerView.h"
#import "EDQuestionModell.h"
@interface EDQuestionSettingViewController ()

@property(nonatomic,strong)EDInfoSettingView * infoView;

@property(nonatomic,strong)EDQuestionModell * fristModel;


@end
@implementation EDQuestionSettingViewController
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.modelsArry = [NSMutableArray array];
    self.fristModel = [EDQuestionModell new];
    
    [self creatUI];
    
    [self loadUser_GetgetgetAllQuestion];
    
}
-(void)creatUI{
    
    switch (self.showType) {
        case 0:
        {
            //安全问题
            EDInfoSettingView * infoView = [[NSBundle mainBundle]loadNibNamed:@"EDInfoSettingView" owner:self options:nil].lastObject;
            infoView.enterTF.placeholder = @"";
            infoView.btnBg.hidden = NO;
            [infoView.daysBtn setTitle:@"您的学校名称是？" forState:0];
            infoView.frame =CGRectMake(0, kStatusBarAndNavigationBarHeight, kScreenWidth, 70);
            [self.view addSubview:infoView];
            self.infoView = infoView;
            WEAKSELF
            [infoView.daysBtn add_BtnClickHandler:^(NSInteger tag) {
                STRONGSELFFor(weakSelf);
            [strongSelf dasBtnsClick:infoView.daysBtn];
            }];
            
            EDInfoSettingView * infoView2 = [[NSBundle mainBundle]loadNibNamed:@"EDInfoSettingView" owner:self options:nil].lastObject;
            infoView2.enterTF.placeholder = @"请输入您的安全答案";
            infoView2.enterTF.tag = 10086;
            infoView2.frame =CGRectMake(0, infoView.bottom+1, kScreenWidth, 70);
            [self.view addSubview:infoView2];
            
            UILabel * tishiKab = [BBControl createLabelWithFrame:CGRectMake(20, infoView2.bottom+20, kScreenWidth-40, 65) Font:14 Text:@"请牢记您的安全问题与答案，这将有助于您的账户安全,提交后无法修改。"];
            tishiKab.numberOfLines = 0;
            tishiKab.textAlignment = NSTextAlignmentCenter;
            tishiKab.textColor =kRGBColor(90, 90, 90 );
            [self.view addSubview:tishiKab];
            
            UIButton * bottomBtn = [BBControl createButtonWithFrame:CGRectMake(60, tishiKab.bottom+20, kScreenWidth-120, 50) target:self SEL:@selector(sureBtnClick:) title:@"保存设置"];
            [bottomBtn setBackgroundImage: [UIImage imageNamed:@"login_Btn_bg"] forState:0];
            [bottomBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
            [bottomBtn setTitleColor:[UIColor whiteColor] forState:0];
            [self.view addSubview:bottomBtn];
   
            
            
        }
            break;
        case 1:
        {
            EDInfoSettingView * infoView = [[NSBundle mainBundle]loadNibNamed:@"EDInfoSettingView" owner:self options:nil].lastObject;
            infoView.enterTF.placeholder = @"请输入微信号码";
            infoView.frame =CGRectMake(0, kStatusBarAndNavigationBarHeight, kScreenWidth, 70);
            [self.view addSubview:infoView];
            UIButton * bottomBtn = [BBControl createButtonWithFrame:CGRectMake(60, infoView.bottom+40, kScreenWidth-120, 50) target:self SEL:@selector(sureBtnClick:) title:@"保存设置"];
            [bottomBtn setBackgroundImage: [UIImage imageNamed:@"login_Btn_bg"] forState:0];
            [bottomBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
            [bottomBtn setTitleColor:[UIColor whiteColor] forState:0];
            [self.view addSubview:bottomBtn];
        }
            break;
        case 2:
        {
            EDInfoSettingView * infoView = [[NSBundle mainBundle]loadNibNamed:@"EDInfoSettingView" owner:self options:nil].lastObject;
            infoView.frame =CGRectMake(0, kStatusBarAndNavigationBarHeight, kScreenWidth, 70);
            infoView.enterTF.placeholder = @"请输入QQ号码";
            [self.view addSubview:infoView];
            UIButton * bottomBtn = [BBControl createButtonWithFrame:CGRectMake(60, infoView.bottom+40, kScreenWidth-120, 50) target:self SEL:@selector(sureBtnClick:) title:@"保存设置"];
            [bottomBtn setBackgroundImage: [UIImage imageNamed:@"login_Btn_bg"] forState:0];
            [bottomBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
            [bottomBtn setTitleColor:[UIColor whiteColor] forState:0];
            [self.view addSubview:bottomBtn];
        }
            break;
        case 3:
        {
   
        }
            break;
            
        default:
            break;
    }
    
}

-(void)loadUser_GetgetgetAllQuestion{
    
    NSArray * localArry = [kUserDefaults objectForKey:@"UserAllQuestion"];
    NSDictionary * friDicc = localArry[0];
    
    self.fristModel = [[EDQuestionModell alloc]initWithDictionary:friDicc error:nil];
    [self.infoView.daysBtn setTitle:self.fristModel.question forState:0];
    
    for (NSDictionary * diccdata in localArry) {
        EDQuestionModell *  queModel = [[EDQuestionModell alloc]initWithDictionary:diccdata error:nil];
        [self.modelsArry addObject:queModel];
    }
    
    
    
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_GetgetgetAllQuestion"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        
        STRONGSELFFor(weakSelf);
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSArray *dictArry = [dict001 jsonArray:@"data"];
        if ([[dict001 jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            if (dictArry.count>0) {
                 [strongSelf.modelsArry removeAllObjects];
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                [userDefault  setValue:dictArry forKey:@"UserAllQuestion"];
                [userDefault synchronize ];
                NSDictionary * friDicc = dictArry[0];
               
                strongSelf.fristModel = [[EDQuestionModell alloc]initWithDictionary:friDicc error:nil];
                [strongSelf.infoView.daysBtn setTitle:strongSelf.fristModel.question forState:0];
                
                for (NSDictionary * diccdata in dictArry) {
                    EDQuestionModell *  queModel = [[EDQuestionModell alloc]initWithDictionary:diccdata error:nil];
                    [strongSelf.modelsArry addObject:queModel];
                }
                
            }
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
        
    } failure:^(id responseObject, NSError *error) {
        //NSLog(@"error----%@",error);
         [WJUnit showMessage:@"请求错误"];

    }];
    
    
    
}
-(void)sureBtnClick:(UIButton *)sender{
    [self.view endEditing:YES];
    switch (self.showType) {
        case 0:
        {
            
            UITextField * enterText = [self.view viewWithTag:10086];
            if (kStringIsEmpty(enterText.text)) {
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1.5 andImageName:@"error" andTitleStr:[NSString stringWithFormat:@"请输入安全问题答案"] andlightStr:@""];
                [toast showLXAlertView];
                return;
            }

            if ([self isBlank:enterText.text]==YES) {
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1.5 andImageName:@"error" andTitleStr:[NSString stringWithFormat:@"安全答案不能包含空格"] andlightStr:@""];
                [toast showLXAlertView];
                return;
            }
            if (enterText.text.length> 20) {
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1.5 andImageName:@"error" andTitleStr:[NSString stringWithFormat:@"答案字符不能超过20"] andlightStr:@""];
                [toast showLXAlertView];
                return;
            }
            
            [self User_SetQuestionRequest];
            
        }
            break;
        case 1:
        {
            
        }
            break;
        case 2:
        {
            
        }
            break;
        case 3:
        {
            
        }
            break;
            
        default:
            break;
    }
    
}

-(void)dasBtnsClick:(UIButton*)sender{
    [self.view endEditing:YES];
    if (self.modelsArry.count==0) {
        
        [self loadUser_GetgetgetAllQuestion];
        return;
    }
    CGXPickerViewManager *manager = [[CGXPickerViewManager alloc]init];
    manager.titleLabelColor= kRGBColor(91, 91, 91); //kRGBColor(44, 143, 219);
    manager.leftBtnBGColor= [UIColor whiteColor];
    manager.rightBtnBGColor= [UIColor whiteColor];
    manager.leftBtnTitleColor= kRGBColor(161, 161, 161);
    manager.rightBtnTitleColor=kRGBColor(44, 143, 219);
    manager.leftBtnborderColor= [UIColor whiteColor];
    manager.rightBtnborderColor= [UIColor whiteColor];
    NSMutableArray * dataArry = [NSMutableArray array];
    for (EDQuestionModell * modell in self.modelsArry) {
        [dataArry addObject:modell.question];
    }
    WEAKSELF
    [CGXPickerView showStringPickerWithTitle:@"请选择安全问题" DataSource:dataArry DefaultSelValue:self.fristModel.question IsAutoSelect:NO Manager:manager ResultBlock:^(id selectValue, id selectRow) {
        NSLog(@"CGXPickerView--%@",selectValue);
        [self.modelsArry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            STRONGSELFFor(weakSelf);
            NSLog(@"%zi %@", idx, obj);
            EDQuestionModell * modell2 = (EDQuestionModell *)obj;
            if ([modell2.question isEqualToString:selectValue]) {
                NSLog(@"------ %zi %@", idx, obj);
                strongSelf.fristModel = modell2;
                [strongSelf.infoView.daysBtn setTitle:modell2.question forState:0];
                *stop = YES;
            }
        }];

    }];
    
}

-(void)User_SetQuestionRequest{
     UITextField * enterText = [self.view viewWithTag:10086];
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_SetQuestion"];
    WEAKSELF
    NSMutableDictionary *  diccc = [NSMutableDictionary dictionary];
    [diccc setValue:self.fristModel.number forKey:@"que"];
     [diccc setValue:enterText.text forKey:@"answer"];
    [[SmileHttpTool sharedInstance] GET :url parameters:diccc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        STRONGSELFFor(weakSelf);
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
        NSLog(@"responseObjectStr----%@",responseObjectStr);
        if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1.5 andImageName:@"success" andTitleStr:[NSString stringWithFormat:@"安全问题设置成功"] andlightStr:@""];
                [toast showLXAlertView];
               
                __block EDQuestionSettingViewController *weakSelf = self;
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    if (weakSelf.dismiss) {
                        weakSelf.dismiss(YES);
                    }
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
        [strongSelf.ks_TableView reloadData];
    } failure:^(id responseObject, NSError *error) {
        NSLog(@"error----%@",error);
        [WJUnit showMessage:@"请求错误"];
    }];
    
    
    
}
/**
 * 判断字符串是否包含空格
 */
-(BOOL)isBlank:(NSString *)str{
    NSRange _range = [str rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        //有空格
        // NSLog(@"有空格");
        return YES;
    }else {
        //没有空格
        // NSLog(@"没有空格");
        return NO;
    }
}


@end
